﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace RAP.Framework.Libary.Utils.Collections.Limited
{
    /// <summary>
    /// 有限长度的队列
    /// </summary>
    public class LimitedQueue : Queue
    {
        protected object _lockObj = new object( );

        /// <summary>
        /// 最大长度
        /// </summary>
        public int Limit { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="limit">队列的最大长度，如果为0，则不限制</param>
        public LimitedQueue( int limit = 0 )
            : base( limit )
        {
            this.Limit = limit;
        }

        /// <summary>
        /// 将对象添加到结尾处。
        /// </summary>
        /// <param name="item"></param>
        public new void Enqueue( object item )
        {
            lock ( _lockObj )
            {
                if ( this.Limit > 0 && this.Count >= this.Limit )
                {
                    this.Dequeue( );
                }
                base.Enqueue( item );
            }
        }
    }

    /// <summary>
    /// 有限长度的队列（泛型）
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class LimitedQueue<T> : LimitedQueue
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="item"></param>
        public void Enqueue( T item )
        {
            base.Enqueue( item );
        }

        /// <summary>
        /// 移除并返回位于开始处的对象。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public new T Dequeue( )
        {
            return ( T )base.Dequeue( );
        }
    }
}
